import React, { useState, useEffect } from 'react';
import { 
  Form, Button, Input, Select, InputNumber, Space, message, 
  Card, Spin, Tabs, Switch 
} from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Question, QuestionType, DifficultyLevel, CreateQuestionRequest } from '@/types/question';
import { questionService } from '@/services/questionService';
import SingleChoiceForm from './components/SingleChoiceForm';
import MultipleChoiceForm from './components/MultipleChoiceForm';
import TrueFalseForm from './components/TrueFalseForm';
import FillBlankForm from './components/FillBlankForm';
import CompositeQuestionForm from './components/CompositeQuestionForm';
import CodeBlockEditor from './components/CodeBlockEditor';
import TagSelector from '@/components/TagSelector';
import { tagService } from '@/services/tagService';

const { Option } = Select;
const { TextArea } = Input;

const QuestionEditor: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [searchParams] = useSearchParams();
  const bankId = searchParams.get('bank_id');

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [questionType, setQuestionType] = useState<QuestionType>(QuestionType.SINGLE_CHOICE);
  const [hasCode, setHasCode] = useState(false);

  // 加载题目数据（编辑模式）
  useEffect(() => {
    if (id) {
      loadQuestion();
    } else if (bankId) {
      form.setFieldsValue({ question_bank: Number(bankId) });
    }
  }, [id, bankId]);

  const loadQuestion = async () => {
    if (!id) return;
    setLoading(true);
    try {
      const response = await questionService.getQuestion(Number(id));
      const question = response.data.data;
      form.setFieldsValue(question);
      setQuestionType(question.type);
      setHasCode(question.has_code || false);
    } catch (error) {
      message.error('加载题目失败');
    } finally {
      setLoading(false);
    }
  };

  // 保存题目
  const handleSave = async (values: any) => {
    setSaving(true);
    try {
      const data: CreateQuestionRequest = {
        ...values,
        type: questionType,
        has_code: hasCode,
      };

      if (id) {
        await questionService.updateQuestion(Number(id), data);
        message.success('题目更新成功');
      } else {
        await questionService.createQuestion(data);
        message.success('题目创建成功');
      }
      
      navigate('/admin/question/list');
    } catch (error: any) {
      message.error(error.response?.data?.message || '保存失败');
    } finally {
      setSaving(false);
    }
  };

  // 根据题型渲染不同的表单
  const renderQuestionForm = () => {
    switch (questionType) {
      case QuestionType.SINGLE_CHOICE:
        return <SingleChoiceForm form={form} />;
      case QuestionType.MULTIPLE_CHOICE:
        return <MultipleChoiceForm form={form} />;
      case QuestionType.TRUE_FALSE:
        return <TrueFalseForm form={form} />;
      case QuestionType.FILL_BLANK:
        return <FillBlankForm form={form} />;
      case QuestionType.COMPOSITE:
        return <CompositeQuestionForm form={form} />;
      default:
        return null;
    }
  };

  if (loading) {
    return <Spin tip="加载中..." />;
  }

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <Space>
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/admin/question/list')}
            >
              返回
            </Button>
            <span>{id ? '编辑题目' : '新建题目'}</span>
          </Space>
        }
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          initialValues={{
            difficulty: DifficultyLevel.MEDIUM,
            tags: [],
            is_active: true,
            has_code: false,
            case_sensitive: false,
          }}
        >
          {/* 基本信息 */}
          <Tabs
            type="card"
            items={[
              {
                key: 'basic',
                label: '基本信息',
                children: (
                  <Space direction="vertical" size="large" style={{ width: '100%' }}>
                    <Form.Item
                      name="type"
                      label="题目类型"
                      rules={[{ required: true, message: '请选择题目类型' }]}
                    >
                      <Select 
                        onChange={(value) => setQuestionType(value)}
                        disabled={!!id}
                        style={{ width: 200 }}
                      >
                        <Option value="single_choice">单选题</Option>
                        <Option value="multiple_choice">多选题</Option>
                        <Option value="true_false">判断题</Option>
                        <Option value="fill_blank">填空题</Option>
                        <Option value="composite">综合题</Option>
                      </Select>
                    </Form.Item>

                    <Form.Item
                      name="title"
                      label="题目标题"
                      rules={[{ max: 500, message: '标题不能超过500个字符' }]}
                    >
                      <Input placeholder="请输入题目标题（可选）" />
                    </Form.Item>

                    <Form.Item
                      name="content"
                      label="题目内容"
                      rules={[{ required: true, message: '请输入题目内容' }]}
                    >
                      <TextArea 
                        rows={4} 
                        placeholder="请输入题目内容/题干"
                      />
                    </Form.Item>

                    {/* 代码块 */}
                    <Form.Item label="题干包含代码">
                      <Switch 
                        checked={hasCode}
                        onChange={setHasCode}
                        checkedChildren="是"
                        unCheckedChildren="否"
                      />
                    </Form.Item>

                    {hasCode && (
                      <CodeBlockEditor 
                        form={form}
                        codeFieldName="code_content"
                        languageFieldName="code_language"
                      />
                    )}

                    <Form.Item
                      name="question_bank"
                      label="所属题库"
                    >
                      <Select 
                        placeholder="选择题库（可选）"
                        allowClear
                        style={{ width: 300 }}
                      >
                        {/* 这里需要从API加载题库列表 */}
                      </Select>
                    </Form.Item>

                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                      <Form.Item
                        name="difficulty"
                        label="难度等级"
                        rules={[{ required: true }]}
                      >
                        <Select>
                          <Option value={1}>非常简单</Option>
                          <Option value={2}>简单</Option>
                          <Option value={3}>中等</Option>
                          <Option value={4}>困难</Option>
                          <Option value={5}>非常困难</Option>
                        </Select>
                      </Form.Item>

                      <Form.Item
                        name="is_active"
                        label="是否启用"
                        valuePropName="checked"
                      >
                        <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                      </Form.Item>
                    </div>

                    <Form.Item
                      name="tags"
                      label="标签"
                    >
                      <TagSelector 
                        value={form.getFieldValue('tags') || []}
                        onChange={(tags) => form.setFieldValue('tags', tags)}
                        fetchTags={tagService.getTags}
                        addTag={tagService.addTag}
                      />
                    </Form.Item>

                    <Form.Item
                      name="source"
                      label="题目来源"
                    >
                      <Input placeholder="例如：NOIP 2020 初赛" />
                    </Form.Item>
                  </Space>
                ),
              },
              {
                key: 'options',
                label: '题目选项',
                children: renderQuestionForm(),
              },
              {
                key: 'explanation',
                label: '解析和提示',
                children: (
                  <Space direction="vertical" size="large" style={{ width: '100%' }}>
                    <Form.Item
                      name="answer_explanation"
                      label="答案解析"
                    >
                      <TextArea 
                        rows={4} 
                        placeholder="请输入答案解析"
                      />
                    </Form.Item>

                    <Form.Item
                      name="hint"
                      label="提示"
                    >
                      <TextArea 
                        rows={2} 
                        placeholder="请输入提示信息（可选）"
                      />
                    </Form.Item>
                  </Space>
                ),
              },
            ]}
          />

          {/* 提交按钮 */}
          <Form.Item style={{ marginTop: 24 }}>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={saving}>
                {id ? '更新' : '创建'}
              </Button>
              <Button onClick={() => navigate('/admin/question/list')}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default QuestionEditor;

